package com.JZ.QM.controller;

import com.JZ.QM.common.dao.AdjustmentRecordDao;
import com.JZ.QM.common.dao.ProductLibraryInfoDao;
import com.JZ.QM.common.entity.*;
import com.JZ.QM.common.utils.CommonResult;
import com.JZ.QM.common.utils.Time;
import com.JZ.QM.dto.*;
import com.JZ.QM.feign.CombinationFeignService;
import com.JZ.QM.feign.DataFeginService;
import com.JZ.QM.feign.UserInfoFeginService;
import com.JZ.QM.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.ChannelCallback;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.UUID;

/**
 * @author lyp
 * @email lyp@gmail.com
 * @date 2020/7/2 14:41
 */
@RestController
@RefreshScope
@Slf4j
@RequestMapping(value="/transaction")
public class TransactionController {

    @Resource
    UserAccountService userAccountService;

    @Resource
    CombinationFeignService combinationFeignService;

    @Resource
    UserInfoFeginService userInfoFeginService;

    @Resource
    WealthAccountService wealthAccountService;

    @Resource
    DataFeginService dataFeginService;

    @Resource
    EntrustRecordService entrustRecordService;

    @Resource
    AdjustmentRecordDao adjustmentRecordDao;

    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    ProductLibraryInfoDao productLibraryInfoDao;

    @Resource
    WealthPositionService wealthPositionService;

    @Resource
    TradeRecordService tradeRecordService;

    @Resource
    NewCombinationInfoService newCombinationInfoService;

    @Resource
    NewCombinationShareService newCombinationShareService;

    @Resource
    RabbitAdmin rabbitAdmin;

    /**
     * 验证账户密码
     * @param userId
     * @param userPassword
     * @return
     */
    @RequestMapping("/verifyPassword")
    public CommonResult verifyPassword(Long userId,String userPassword){
        //平台账户实体类
        UserAccountEntity userAccountEntity = new UserAccountEntity();
        //密码解析
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        //密码判断flag
        boolean passwordFlag = false;

        userAccountEntity = userAccountService.getAccount(userId);

        passwordFlag = bCryptPasswordEncoder.matches(userPassword,userAccountEntity.getUserPassword());

        if(passwordFlag){
            return CommonResult.success("密码输入正确");
        }else {
            return CommonResult.error(201,"密码输入错误");
        }

    }

    /**
     * 验证风险类型是否匹配
     * @param userId
     * @param comBaseId
     * @return
     */
    @RequestMapping("/verifyRiskLevel")
    public CommonResult verifyRiskLevel(Long userId,Long comBaseId){
        //组合产品的实体
        LinkedHashMap combinationBaseInfoEntityMap = new LinkedHashMap();
        //用户实体
        LinkedHashMap userEntityMap = new LinkedHashMap();

        combinationBaseInfoEntityMap = (LinkedHashMap) combinationFeignService.getComBaseInfo(comBaseId).get("combination");

        userEntityMap = (LinkedHashMap) userInfoFeginService.getUserInfoEntity(userId).get("userInfoEntity");

        if(((Integer) combinationBaseInfoEntityMap.get("comBaseRiskLevel") ) <= (Integer.valueOf((String) userEntityMap.get("userRisk")))) {
            return CommonResult.success("风险等级匹配");
        }else{
            return CommonResult.error(201,"风险等级不匹配");
        }
    }

    /**
     * 验证账户余额
     * @param userId
     * @param amount
     * @return
     */
    @RequestMapping("/verifyAccountAmount")
    public CommonResult verifyAccountAmount(Long userId, BigDecimal amount){
        //用户平台账号实体
        UserAccountEntity userAccountEntity = new UserAccountEntity();

        userAccountEntity = userAccountService.quaryByUserId(userId);

        if(userAccountEntity != null){
            if(userAccountEntity.getAccountAmoount().compareTo(amount) == 1){
                return CommonResult.success("余额充足");
            }else {
                return CommonResult.error(201,"余额不足,请充值");
            }
        }else {
            return CommonResult.error(501,"账户不存在");
        }
    }

    /**
     * 产品购买试算
     * @param comBaseId
     * @param amount
     * @return
     */
    @RequestMapping("/trialCalculation")
    public CommonResult trialCalculation(Long comBaseId, Long userId, BigDecimal amount){
        //股票产品列表
        ArrayList<LinkedHashMap> stockList = new ArrayList<>();
        //基金产品列表
        ArrayList<LinkedHashMap> fundList = new ArrayList<>();
        //试算结果集
        ArrayList<TrialCalculationDto> trialCalculationDtos = new ArrayList<>();
        //试算总金额
        BigDecimal realTotalAmount = BigDecimal.valueOf(0.0000);
        //搓和份额剩余金额
        BigDecimal remainAmount = BigDecimal.valueOf(0.0000);
        //原传入组合id
        Long oldComBaseId = comBaseId;
        //如果是用户已经自定义过的组合，应该换成自定义的组合id
        comBaseId = verifyUpdateNewComId(userId,comBaseId);

        log.info(String.valueOf(comBaseId));
        //用户修改后的组合
        if(oldComBaseId == comBaseId){
            stockList = (ArrayList<LinkedHashMap>) combinationFeignService.getCombinationShareList(comBaseId).get("stockList");

            fundList = (ArrayList<LinkedHashMap>) combinationFeignService.getCombinationShareList(comBaseId).get("fundList");
        }else{
            stockList = (ArrayList<LinkedHashMap>) dataFeginService.getCombinationShareList(comBaseId).get("stockList");

            fundList = (ArrayList<LinkedHashMap>) dataFeginService.getCombinationShareList(comBaseId).get("fundList");
        }
        if(!stockList.isEmpty()){
            //按比例分配金额,并计算股票份额,
            for (LinkedHashMap stockShareEntity:stockList) {
                //试算Dto实体
                TrialCalculationDto trialCalculationDto = new TrialCalculationDto();
                //份额计算
                BigDecimal partAmount = BigDecimal.valueOf(0);
                if(oldComBaseId != comBaseId){
                    partAmount = amount.multiply(BigDecimal.valueOf((Double) stockShareEntity.get("newComShareRadio")));
                }else{
                    partAmount = amount.multiply(BigDecimal.valueOf((Double) stockShareEntity.get("comShareRadio")));
                }
                BigDecimal closePrice = BigDecimal.valueOf((Double) dataFeginService.getPrice((String) stockShareEntity.get("proTsCode")).get("closePrice"));
                BigDecimal stockShare = partAmount.divide(closePrice,0,1);
                BigDecimal realAmount = stockShare.multiply(closePrice);
                remainAmount = remainAmount.add(partAmount.subtract(realAmount));

                trialCalculationDto.setAmount(realAmount);
                trialCalculationDto.setProTsCode((String) stockShareEntity.get("proTsCode"));
                trialCalculationDto.setProName(String.valueOf( combinationFeignService.getProName( (String) stockShareEntity.get("proTsCode")).get("proName")));

                trialCalculationDtos.add(trialCalculationDto);
            }
        }

        if(!fundList.isEmpty()){
            //按比例分配金额,并计算基金份额,
            for (LinkedHashMap fundShareEntity:fundList) {
                //试算Dto实体
                TrialCalculationDto trialCalculationDto = new TrialCalculationDto();
                //份额计算
                BigDecimal partAmount = BigDecimal.valueOf(0);
                if(oldComBaseId != comBaseId){
                    partAmount = amount.multiply(BigDecimal.valueOf((Double) fundShareEntity.get("newComShareRadio")));
                }else{
                    partAmount = amount.multiply(BigDecimal.valueOf((Double) fundShareEntity.get("comShareRadio")));
                }
                BigDecimal closePrice = BigDecimal.valueOf((Double) dataFeginService.getPrice((String) fundShareEntity.get("proTsCode")).get("closePrice"));
                BigDecimal fundShare = partAmount.divide(closePrice,0,1);
                BigDecimal realAmount = fundShare.multiply(closePrice);
                remainAmount = remainAmount.add(partAmount.subtract(realAmount));

                trialCalculationDto.setAmount(realAmount);
                trialCalculationDto.setProTsCode((String) fundShareEntity.get("proTsCode"));
                trialCalculationDto.setProName(String.valueOf( combinationFeignService.getProName( (String) fundShareEntity.get("proTsCode")).get("proName")));

                trialCalculationDtos.add(trialCalculationDto);
            }
        }
        realTotalAmount = amount.subtract(remainAmount);

        //计算各成分产品金额占比
        for (TrialCalculationDto trialCalculationDto:trialCalculationDtos) {
            BigDecimal ratio = trialCalculationDto.getAmount().divide(realTotalAmount,2, RoundingMode.HALF_UP);
            trialCalculationDto.setRatio(String.valueOf(ratio.multiply(BigDecimal.valueOf(100)))+"%");
        }

        return CommonResult.success("试算成功")
                .put("realTotalAmount",realTotalAmount)
                .put("trialCalculationList",trialCalculationDtos);
    }

    /**
     * 购买产品
     * @param userId
     * @param comBaseId
     * @param amount
     * @return
     */
    @Transactional
    @RequestMapping("/merchandise")
    public CommonResult merchandise(Long userId, Long comBaseId, BigDecimal amount, BigDecimal merchandiseAmount){
        //用户平台账号实体
        UserAccountEntity userAccountEntity = new UserAccountEntity();
        //交易记录实体
        TradeRecordEntity tradeRecordEntity = new TradeRecordEntity();
        //财富账号实体
        WealthAccountEntity wealthAccountEntity =  new WealthAccountEntity();
        //转账flag
        boolean transferFlag = true;
        //股票产品列表
        ArrayList<LinkedHashMap> stockList = new ArrayList<>();
        //基金产品列表
        ArrayList<LinkedHashMap> fundList = new ArrayList<>();
        //股票委托列表
        ArrayList<EntrustRecordEntity> stockEntrustList = new ArrayList<>();
        //基金委托列表
        ArrayList<EntrustRecordEntity> fundEntrustList = new ArrayList<>();
        //股票委托保存flag
        boolean stockEntrustFlag = true;
        //基金委托保存flag
        boolean fundEntrustFlag = true;
        //用于获取组合名称
        Long nameId = comBaseId;
        //更新购买人数
        dataFeginService.updateCombinationDynamicInfo(nameId,0,0,1,1);
        //如果是用户已经自定义过的组合，应该换成自定义的组合id
        comBaseId = verifyUpdateNewComId(userId,comBaseId);

        userAccountEntity = userAccountService.quaryByUserId(userId);

        //创建财富账号，将资金从平台账号到财富账号,并创建资金流水记录
        tradeRecordEntity = wealthAccountService.transferAmount(userAccountEntity.getAccountId(),nameId,merchandiseAmount,userId);

        if(tradeRecordEntity == null){
            return CommonResult.error(201,"转账失败");
        }
        wealthAccountEntity = wealthAccountService.getById(tradeRecordEntity.getRelevanceAccountId());

        //用户修改后的组合
        if(wealthAccountEntity.getIsUpdate() == 1){
            stockList = (ArrayList<LinkedHashMap>) dataFeginService.getCombinationShareList(comBaseId).get("stockList");

            fundList = (ArrayList<LinkedHashMap>) dataFeginService.getCombinationShareList(comBaseId).get("fundList");
        }else{
            stockList = (ArrayList<LinkedHashMap>) combinationFeignService.getCombinationShareList(comBaseId).get("stockList");

            fundList = (ArrayList<LinkedHashMap>) combinationFeignService.getCombinationShareList(comBaseId).get("fundList");
        }

        if(!stockList.isEmpty()){
            //按比例分配金额,并计算股票份额
            for (LinkedHashMap stockShareEntity:stockList) {
                //委托实体类
                EntrustRecordEntity entrustRecordEntity = new EntrustRecordEntity();

                //份额计算
                BigDecimal partAmount = BigDecimal.valueOf(0);
                if(wealthAccountEntity.getIsUpdate() == 1){
                    partAmount = amount.multiply(BigDecimal.valueOf((Double) stockShareEntity.get("newComShareRadio")));
                }else{
                    partAmount = amount.multiply(BigDecimal.valueOf((Double) stockShareEntity.get("comShareRadio")));
                }

                BigDecimal closePrice = BigDecimal.valueOf((Double) dataFeginService.getPrice((String) stockShareEntity.get("proTsCode")).get("closePrice"));
                BigDecimal stockShare = partAmount.divide(closePrice,0,1);
                BigDecimal realAmount = stockShare.multiply(closePrice);


                //组装股票委托
                //进行委托流水号的组装
                String logicId = "SE" + UUID.randomUUID();
                entrustRecordEntity.setEntrustAmount(realAmount);
                entrustRecordEntity.setEntrustShare(Integer.valueOf(stockShare.toString()));
                entrustRecordEntity.setEntrustType(2);
                entrustRecordEntity.setEntrustStatus(1);
                entrustRecordEntity.setProId(Long.valueOf(String.valueOf(combinationFeignService.getProId((String) stockShareEntity.get("proTsCode")).get("proId"))));
                entrustRecordEntity.setUserId(userId);
                entrustRecordEntity.setWealthAccountId(wealthAccountEntity.getWealthAccountId());
                entrustRecordEntity.setLogicId(logicId);
                entrustRecordEntity.setTradeId(tradeRecordEntity.getTradeId());

                boolean saveFlag = entrustRecordService.save(entrustRecordEntity);

                stockEntrustFlag &= saveFlag;

                //将其保存，待之后发往消息队列
                if(saveFlag){
                    stockEntrustList.add(entrustRecordEntity);
                }
            }
        }

        if(!fundList.isEmpty()){
            //按比例分配金额,并计算基金份额,
            for (LinkedHashMap fundShareEntity:fundList) {
                //委托实体类
                EntrustRecordEntity entrustRecordEntity = new EntrustRecordEntity();

                //份额计算
                BigDecimal partAmount = BigDecimal.valueOf(0);
                if(wealthAccountEntity.getIsUpdate() == 1){
                    partAmount = amount.multiply(BigDecimal.valueOf((Double) fundShareEntity.get("newComShareRadio")));
                }else{
                    partAmount = amount.multiply(BigDecimal.valueOf((Double) fundShareEntity.get("comShareRadio")));
                }
                BigDecimal closePrice = BigDecimal.valueOf((Double) dataFeginService.getPrice((String) fundShareEntity.get("proTsCode")).get("closePrice"));
                BigDecimal fundShare = partAmount.divide(closePrice,0,1);
                BigDecimal realAmount = fundShare.multiply(closePrice);
                //组装股票委托
                //进行委托流水号的组装
                String logicId = "FE" + UUID.randomUUID();

                entrustRecordEntity.setEntrustAmount(realAmount);
                entrustRecordEntity.setEntrustShare(Integer.valueOf(fundShare.toString()));
                entrustRecordEntity.setEntrustType(2);
                entrustRecordEntity.setEntrustStatus(1);
                entrustRecordEntity.setProId(Long.valueOf(String.valueOf(combinationFeignService.getProId((String) fundShareEntity.get("proTsCode")).get("proId"))));
                entrustRecordEntity.setUserId(userId);
                entrustRecordEntity.setWealthAccountId(wealthAccountEntity.getWealthAccountId());
                entrustRecordEntity.setLogicId(logicId);
                entrustRecordEntity.setTradeId(tradeRecordEntity.getTradeId());

                boolean saveFlag = entrustRecordService.save(entrustRecordEntity);

                fundEntrustFlag &= saveFlag;
                //将其发送到消息队列中
                if(saveFlag){
                    fundEntrustList.add(entrustRecordEntity);
                }
            }
        }

        if(! (stockEntrustFlag && fundEntrustFlag)){
            return CommonResult.error(501,"委托失败,系统故障");
        }else{
            //将委托发往基金公司
            for (EntrustRecordEntity fundEntrust:stockEntrustList) {
                rabbitTemplate.convertAndSend("myExchange","fundTask",fundEntrust);
            }
            //将委托发往股票交易所
            for (EntrustRecordEntity stockEntrust:fundEntrustList) {
                rabbitTemplate.convertAndSend("myExchange","stockTask",stockEntrust);
            }

            LinkedHashMap comBaseInfo = (LinkedHashMap) combinationFeignService.getComBaseInfo(nameId).get("combination");
            //组合名称
            String comBaseName = (String) comBaseInfo.get("comBaseName");

            SimpleDateFormat df1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //下单时间
            String createTime = df1.format(tradeRecordEntity.getGmtCreate());
            //金额
            BigDecimal tradeAmount = tradeRecordEntity.getTradeAmoount();
            //交易类型
            String tradeType = "申购";
            SimpleDateFormat df2=new SimpleDateFormat("MM-dd");
            //确认份额日期
            String confirmShareTime = df2.format(new Date(tradeRecordEntity.getGmtCreate().getTime() + 1 * 24 * 60 * 60 * 1000));
            //查看收益日期
            String viewEarningsTime = df2.format(new Date(tradeRecordEntity.getGmtCreate().getTime() + 2 * 24 * 60 * 60 * 1000));

            return CommonResult.success("委托成功，待处理")
                    .put("comBaseName",comBaseName)
                    .put("createTime",createTime)
                    .put("tradeAmount",tradeAmount)
                    .put("tradeType",tradeType)
                    .put("confirmShareTime",confirmShareTime)
                    .put("viewEarningsTime",viewEarningsTime);
        }
    }

    /**
     * 撤单请求
     * @param comBaseId
     * @param userId
     * @param type  0 表示撤销买入单  1 表示撤销赎回单
     * @return
     */
    @RequestMapping("/cancelOrder")
    public CommonResult cancelOrder(Long comBaseId,Long userId,Integer type){
        //股票撤单flag
        boolean stockCancelFlag = true;
        //基金撤单flag
        boolean fundCancelFlag = true;
        //交易记录id
        Long tradeId = Long.valueOf(0);
        //交易记录实体
        TradeRecordEntity tradeRecordEntity = new TradeRecordEntity();
        //股票委托数量
        int numStockEntrust = 0;
        //基金委托数量
        int numFundEntrust = 0;
        //财富账号id
        Long wealthAccountId = Long.valueOf(0);
        //消息队列名称
        String stockMessageQueue = "";
        String fundMessageQueue = "";
        //路由键名称
        String stockMessageRouteKey = "";
        String fundMessageRouteKey = "";

        //撤销买入单
        if(type == 0){
            stockMessageQueue = "stockQueue";
            fundMessageQueue = "fundQueue";

            stockMessageRouteKey = "stockTask";
            fundMessageRouteKey = "fundTask";

            //撤销赎回单
        }else {
            stockMessageQueue = "stockRedemptionQueue";
            fundMessageQueue = "fundRedemptionQueue";

            stockMessageRouteKey = "stockRedemptionTask";
            fundMessageRouteKey = "fundRedemptionTask";
        }

        //根据组合产品id和用户id查询财富账号id
        wealthAccountId = wealthAccountService.getWealthAccount(comBaseId,userId).getWealthAccountId();

        numStockEntrust = getMessageCount(stockMessageQueue);

        numFundEntrust = getMessageCount(fundMessageQueue);

        for (int i = 0; i <numStockEntrust ; i++) {
            //从消息队列中获取消息
            EntrustRecordEntity entrustRecordEntity = (EntrustRecordEntity) rabbitTemplate.receiveAndConvert(stockMessageQueue);

            //需要判断是否是当前撤单的用户的委托
            if( entrustRecordEntity.getWealthAccountId() == wealthAccountId ){

                //设置委托状态为撤单
                entrustRecordEntity.setEntrustStatus(3);

                tradeId = entrustRecordEntity.getTradeId();

                boolean cancelFlag = entrustRecordService.saveOrUpdate(entrustRecordEntity);

                stockCancelFlag &= cancelFlag;

                if(cancelFlag){
                    log.info("委托流水号:"+entrustRecordEntity.getLogicId()+"===>"+"撤单成功");
                }else {
                    log.info("委托流水号:"+entrustRecordEntity.getLogicId()+"===>"+"撤单失败");
                }
            }else {
                rabbitTemplate.convertAndSend("myExchange",stockMessageRouteKey,entrustRecordEntity);
            }
        }

        for (int i = 0; i <numFundEntrust ; i++) {

            //从消息队列中获取消息
            EntrustRecordEntity entrustRecordEntity = (EntrustRecordEntity) rabbitTemplate.receiveAndConvert(fundMessageQueue);

            //需要判断是否是当前撤单的用户的委托
            if(entrustRecordEntity.getWealthAccountId() == wealthAccountId ){
                //设置委托状态为撤单
                entrustRecordEntity.setEntrustStatus(3);

                tradeId = entrustRecordEntity.getTradeId();

                boolean cancelFlag = entrustRecordService.saveOrUpdate(entrustRecordEntity);

                fundCancelFlag &= cancelFlag;

                if(cancelFlag){
                    log.info("委托流水号:"+entrustRecordEntity.getLogicId()+"===>"+"撤单成功");
                }else {
                    log.info("委托流水号:"+entrustRecordEntity.getLogicId()+"===>"+"撤单失败");
                }
            }else {
                rabbitTemplate.convertAndSend("myExchange",fundMessageRouteKey,entrustRecordEntity);
            }
        }

        if(stockCancelFlag && fundCancelFlag){
                //买入撤单
            if(0 == type){
                //将钱从财富账号上转回到平台账号上以及返回交易流水
                tradeRecordEntity = wealthAccountService.transferBackAmount(wealthAccountId, userId,3,tradeId);

                LinkedHashMap comBaseInfo = (LinkedHashMap) combinationFeignService.getComBaseInfo(comBaseId).get("combination");
                //组合名称
                String comBaseName = (String) comBaseInfo.get("comBaseName");

                SimpleDateFormat df1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //下单时间
                String createTime = df1.format(tradeRecordEntity.getGmtCreate());
                //金额
                BigDecimal tradeAmount = tradeRecordEntity.getTradeAmoount();
                //交易类型
                String tradeType = "撤单";

                if(tradeRecordEntity != null){
                    return CommonResult.success("撤单成功")
                            .put("comBaseName",comBaseName)
                            .put("createTime",createTime)
                            .put("tradeAmount",tradeAmount)
                            .put("tradeType",tradeType);
                }else {
                    return CommonResult.error(201,"撤单失败");
                }
                //赎回撤单
            }else {
                tradeRecordEntity = tradeRecordService.getById(tradeId);
                tradeRecordEntity.setTradeCategory(3);

                LinkedHashMap comBaseInfo = (LinkedHashMap) combinationFeignService.getComBaseInfo(comBaseId).get("combination");
                //组合名称
                String comBaseName = (String) comBaseInfo.get("comBaseName");

                SimpleDateFormat df1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //下单时间
                String createTime = df1.format(tradeRecordEntity.getGmtCreate());
                //金额
                BigDecimal tradeAmount = tradeRecordEntity.getTradeAmoount();
                //交易类型
                String tradeType = "撤单";

                boolean updateFlag =  tradeRecordService.saveOrUpdate(tradeRecordEntity);

                if(updateFlag){
                    return CommonResult.success("撤单成功")
                            .put("comBaseName",comBaseName)
                            .put("createTime",createTime)
                            .put("tradeAmount",tradeAmount)
                            .put("tradeType",tradeType);
                }else {
                    return CommonResult.error(201,"撤单失败");
                }
            }
        }else {
            return CommonResult.error(201,"撤单失败");
        }
    }

    /**
     * 赎回金额验证
     * @param userId
     * @param comBaseId
     * @return
     */
    @RequestMapping("/verifyRedemptionAmount")
    public CommonResult verifyRedemptionAmount(Long userId, Long comBaseId){
        //财富账号实体类
        WealthAccountEntity wealthAccountEntity = new WealthAccountEntity();
        //先通过用户id和组合产品id获取财富产品账号
        wealthAccountEntity = wealthAccountService.getWealthAccount(comBaseId,userId);

        if(wealthAccountEntity != null){
            return CommonResult.success().put("RedeemableAmount",wealthAccountEntity.getWealthAccountAmoount());
        }else{
            return CommonResult.error(501,"无此持仓");
        }
    }

    /**
     * 产品赎回
     * @param userId
     * @param comBaseId
     * @param amount
     * @param totalRedemptionIndex 是否全部赎回，标志位， 1  全部赎回  0 部分赎回
     * @return
     */
    @Transactional
    @RequestMapping("/redemption")
    public CommonResult redemption(Long userId, Long comBaseId, BigDecimal amount, Integer totalRedemptionIndex) throws ParseException {
        //交易流水实体
        TradeRecordEntity tradeRecordEntity = new TradeRecordEntity();
        //更新交易人数
        dataFeginService.updateCombinationDynamicInfo(comBaseId,0,0,1,0);
        //全部赎回
        if(totalRedemptionIndex == 1){
            //当前产品的持仓列表
            ArrayList<WealthPositionEntity> wealthPositionEntityArrayList = new ArrayList<>();
            //股票委托列表
            ArrayList<EntrustRecordEntity> stockEntrusArrayList = new ArrayList<>();
            //基金委托列表
            ArrayList<EntrustRecordEntity> fundEntrusArrayList =  new ArrayList<>();
            //财富账号实体类
            WealthAccountEntity wealthAccountEntity = new WealthAccountEntity();
            //产品类型 1是股票 0是基金
            Integer proType = 0;
            //委托保存flag
            boolean saveFlag = true;

            //先通过用户id和组合产品id获取财富产品账号
            wealthAccountEntity = wealthAccountService.getWealthAccount(comBaseId,userId);

            wealthPositionEntityArrayList = wealthPositionService.getListByWealthAccountId(wealthAccountEntity.getWealthAccountId());
            //依据当前持仓列表构建委托类，全部赎回
            for (WealthPositionEntity wealthPositionEntity:wealthPositionEntityArrayList) {
                //委托实体类
                EntrustRecordEntity entrustRecordEntity = new EntrustRecordEntity();

                entrustRecordEntity.setEntrustStatus(1);
                entrustRecordEntity.setEntrustAmount(wealthPositionEntity.getPositionAmount());
                entrustRecordEntity.setEntrustShare(wealthPositionEntity.getPositionShare());
                entrustRecordEntity.setWealthAccountId(wealthPositionEntity.getWealthAccountId());
                entrustRecordEntity.setProId(wealthPositionEntity.getProId());
                entrustRecordEntity.setUserId(wealthPositionEntity.getUserId());
                entrustRecordEntity.setEntrustType(1);
                //通过产品id查询是股票产品或者基金产品
                proType = (Integer) combinationFeignService.getProType(wealthPositionEntity.getProId()).get("proType");

                if(proType == 1) {
                    //进行委托流水号的组装
                    String logicId = "SE" + UUID.randomUUID();
                    entrustRecordEntity.setLogicId(logicId);

                    stockEntrusArrayList.add(entrustRecordEntity);
                }else {
                    //进行委托流水号的组装
                    String logicId = "FE" + UUID.randomUUID();
                    entrustRecordEntity.setLogicId(logicId);

                    fundEntrusArrayList.add(entrustRecordEntity);
                }
            }

            //发送委托到股票交易所和基金公司,并生成交易流水
            if(saveFlag){
                //扣除费之后的赎回总金额
                BigDecimal redemptionAmount = BigDecimal.valueOf(0);
                //赎回费率
                BigDecimal ratio = BigDecimal.valueOf(0);
                //获取建仓时间
                Date update = wealthAccountEntity.getGmtCreate();
                //计算持有时长
                Date now = new Date();
                int days = Time.daysBetween(now, update);

                if(days <= 7){
                    ratio = BigDecimal.valueOf(0.015);
                }else if( 7 < days && days <= 30){
                    ratio = BigDecimal.valueOf(0.01);
                }else {
                    ratio = BigDecimal.valueOf(0.005);
                }

                for (EntrustRecordEntity stockEntrust:stockEntrusArrayList) {
                    redemptionAmount = redemptionAmount.add(stockEntrust.getEntrustAmount().multiply(BigDecimal.valueOf(1).subtract(ratio)));
                }
                for (EntrustRecordEntity fundEntrust:fundEntrusArrayList) {
                    redemptionAmount = redemptionAmount.add(fundEntrust.getEntrustAmount().multiply(BigDecimal.valueOf(1).subtract(ratio)));
                }

                //进行资金流水号的组装
                String timeUUid = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                String logicId = "QMT" + timeUUid;

                tradeRecordEntity.setLogicId(logicId);
                tradeRecordEntity.setTradeAmoount(redemptionAmount);
                tradeRecordEntity.setRelevanceAccountId(wealthAccountEntity.getWealthAccountId());
                tradeRecordEntity.setRelevanceAccountType(2);
                //设置交易类型
                tradeRecordEntity.setTradeType(1);
                tradeRecordEntity.setTradeCategory(0);
                tradeRecordEntity.setUserId(userId);

                boolean saveTradeRecordFlag = tradeRecordService.save(tradeRecordEntity);

                if(saveTradeRecordFlag){
                    for (EntrustRecordEntity stockEntrust:stockEntrusArrayList) {
                        stockEntrust.setTradeId(tradeRecordEntity.getTradeId());

                        saveFlag &= entrustRecordService.save(stockEntrust);

                        rabbitTemplate.convertAndSend("myExchange","stockRedemptionTask",stockEntrust);
                    }
                    for (EntrustRecordEntity fundEntrust:fundEntrusArrayList) {
                        fundEntrust.setTradeId(tradeRecordEntity.getTradeId());

                        saveFlag &= entrustRecordService.save(fundEntrust);

                        rabbitTemplate.convertAndSend("myExchange","fundRedemptionTask",fundEntrust);
                    }

                    LinkedHashMap comBaseInfo = new LinkedHashMap();
                    //组合名称
                    String comBaseName = "";

                    comBaseInfo = (LinkedHashMap) combinationFeignService.getComBaseInfo(comBaseId).get("combination");
                    comBaseName = (String) comBaseInfo.get("comBaseName");

                    SimpleDateFormat df1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //下单时间
                    String createTime = df1.format(tradeRecordEntity.getGmtCreate());
                    //金额
                    BigDecimal tradeAmount = tradeRecordEntity.getTradeAmoount();
                    //交易类型
                    String tradeType = "赎回";
                    SimpleDateFormat df2=new SimpleDateFormat("MM-dd");
                    //确认份额日期
                    String confirmShareTime = df2.format(new Date(tradeRecordEntity.getGmtCreate().getTime() + 1 * 24 * 60 * 60 * 1000));
                    //查看收益日期
                    String viewEarningsTime = df2.format(new Date(tradeRecordEntity.getGmtCreate().getTime() + 2 * 24 * 60 * 60 * 1000));

                    return CommonResult.success("赎回委托已提交，处理中")
                            .put("comBaseName",comBaseName)
                            .put("createTime",createTime)
                            .put("tradeAmount",tradeAmount)
                            .put("tradeType",tradeType)
                            .put("confirmShareTime",confirmShareTime)
                            .put("viewEarningsTime",viewEarningsTime);
                }else {
                    return CommonResult.error(201,"委托失败,请重新提交");
                }
            }else {
                return CommonResult.error(201,"委托失败,请重新提交");
            }
            //部分赎回
        }else {
            //股票产品列表
            ArrayList<LinkedHashMap> stockList = new ArrayList<>();
            //基金产品列表
            ArrayList<LinkedHashMap> fundList = new ArrayList<>();
            //股票委托列表
            ArrayList<EntrustRecordEntity> stockEntrustList = new ArrayList<>();
            //基金委托列表
            ArrayList<EntrustRecordEntity> fundEntrustList = new ArrayList<>();
            //财富账号
            WealthAccountEntity wealthAccountEntity = new WealthAccountEntity();
            //股票委托保存flag
            boolean stockEntrustFlag = true;
            //基金委托保存flag
            boolean fundEntrustFlag = true;
            //原传入组合id
            Long oldComBaseId = comBaseId;
            //如果是用户已经自定义过的组合，应该换成自定义的组合id
            comBaseId = verifyUpdateNewComId(userId,comBaseId);
            //用户修改后的组合
            if(oldComBaseId == comBaseId){
                stockList = (ArrayList<LinkedHashMap>) combinationFeignService.getCombinationShareList(comBaseId).get("stockList");

                fundList = (ArrayList<LinkedHashMap>) combinationFeignService.getCombinationShareList(comBaseId).get("fundList");
            }else{
                stockList = (ArrayList<LinkedHashMap>) dataFeginService.getCombinationShareList(comBaseId).get("stockList");

                fundList = (ArrayList<LinkedHashMap>) dataFeginService.getCombinationShareList(comBaseId).get("fundList");
            }

            //先通过用户id和组合产品id获取财富产品账号
            wealthAccountEntity = wealthAccountService.getWealthAccount(oldComBaseId,userId);

            if(!stockList.isEmpty()){
                //按比例分配金额,并计算股票份额,
                for (LinkedHashMap stockShareEntity:stockList) {
                    //委托实体类
                    EntrustRecordEntity entrustRecordEntity = new EntrustRecordEntity();
                    //份额计算
                    BigDecimal partAmount = BigDecimal.valueOf(0);
                    if(oldComBaseId != comBaseId){
                        partAmount = amount.multiply(BigDecimal.valueOf((Double) stockShareEntity.get("newComShareRadio")));
                    }else{
                        partAmount = amount.multiply(BigDecimal.valueOf((Double) stockShareEntity.get("comShareRadio")));
                    }
                    BigDecimal closePrice = BigDecimal.valueOf((Double) dataFeginService.getPrice((String) stockShareEntity.get("proTsCode")).get("closePrice"));

                    BigDecimal stockShare = partAmount.divide(closePrice,0,1);

                    //组装股票委托
                    //进行委托流水号的组装
                    String logicId = "SE" + UUID.randomUUID();
                    entrustRecordEntity.setEntrustAmount(stockShare.multiply(closePrice));
                    entrustRecordEntity.setEntrustShare(Integer.valueOf(stockShare.toString()));
                    entrustRecordEntity.setEntrustType(1);
                    entrustRecordEntity.setEntrustStatus(1);
                    entrustRecordEntity.setProId(Long.valueOf(String.valueOf(combinationFeignService.getProId((String) stockShareEntity.get("proTsCode")).get("proId"))));
                    entrustRecordEntity.setUserId(userId);
                    entrustRecordEntity.setWealthAccountId(wealthAccountEntity.getWealthAccountId());
                    entrustRecordEntity.setLogicId(logicId);

                    stockEntrustList.add(entrustRecordEntity);
                }
            }

            if(!fundList.isEmpty()){
                //按比例分配金额,并计算基金份额,
                for (LinkedHashMap fundShareEntity:fundList) {
                    //委托实体类
                    EntrustRecordEntity entrustRecordEntity = new EntrustRecordEntity();
                    //份额计算
                    BigDecimal partAmount = BigDecimal.valueOf(0);
                    if(oldComBaseId != comBaseId){
                        partAmount = amount.multiply(BigDecimal.valueOf((Double) fundShareEntity.get("newComShareRadio")));
                    }else{
                        partAmount = amount.multiply(BigDecimal.valueOf((Double) fundShareEntity.get("comShareRadio")));
                    }
                    BigDecimal closePrice = BigDecimal.valueOf((Double) dataFeginService.getPrice((String) fundShareEntity.get("proTsCode")).get("closePrice"));
                    BigDecimal fundShare = partAmount.divide(closePrice,0,1);
                    //组装股票委托
                    //进行委托流水号的组装
                    String logicId = "FE" + UUID.randomUUID();

                    entrustRecordEntity.setEntrustAmount(partAmount);
                    entrustRecordEntity.setEntrustShare(Integer.valueOf(fundShare.toString()));
                    entrustRecordEntity.setEntrustType(1);
                    entrustRecordEntity.setEntrustStatus(1);
                    entrustRecordEntity.setProId(Long.valueOf(String.valueOf(combinationFeignService.getProId((String) fundShareEntity.get("proTsCode")).get("proId"))));
                    entrustRecordEntity.setUserId(userId);
                    entrustRecordEntity.setWealthAccountId(wealthAccountEntity.getWealthAccountId());
                    entrustRecordEntity.setLogicId(logicId);

                    fundEntrustList.add(entrustRecordEntity);
                }
            }

            if(! (stockEntrustFlag && fundEntrustFlag)){
                return CommonResult.error(501,"委托失败,系统故障");
            }else{
                //扣除费之后的赎回总金额
                BigDecimal redemptionAmount = BigDecimal.valueOf(0);
                //赎回费率
                BigDecimal ratio = BigDecimal.valueOf(0);
                //获取建仓时间
                Date update = wealthAccountEntity.getGmtCreate();
                //计算持有时长
                Date now = new Date();
                int days = Time.daysBetween(now, update);

                if(days <= 7){
                    ratio = BigDecimal.valueOf(0.015);
                }else if( 7 < days && days <= 30){
                    ratio = BigDecimal.valueOf(0.01);
                }else {
                    ratio = BigDecimal.valueOf(0.005);
                }

                for (EntrustRecordEntity fundEntrust:stockEntrustList) {
                    redemptionAmount = redemptionAmount.add(fundEntrust.getEntrustAmount().multiply(BigDecimal.valueOf(1).subtract(ratio)));
                }

                for (EntrustRecordEntity stockEntrust:fundEntrustList) {
                    redemptionAmount = redemptionAmount.add(stockEntrust.getEntrustAmount().multiply(BigDecimal.valueOf(1).subtract(ratio)));
                }

                //进行资金流水号的组装
                String timeUUid = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                String logicId = "QMT" + timeUUid;

                tradeRecordEntity.setLogicId(logicId);
                tradeRecordEntity.setTradeAmoount(redemptionAmount);
                tradeRecordEntity.setRelevanceAccountId(wealthAccountEntity.getWealthAccountId());
                tradeRecordEntity.setRelevanceAccountType(2);
                //设置交易类型
                tradeRecordEntity.setTradeType(1);
                tradeRecordEntity.setTradeCategory(0);
                tradeRecordEntity.setUserId(userId);

                boolean saveTradeRecordFlag = tradeRecordService.save(tradeRecordEntity);

                if(saveTradeRecordFlag){

                    //将委托发往基金公司
                    for (EntrustRecordEntity fundEntrust:stockEntrustList) {

                        fundEntrust.setTradeId(tradeRecordEntity.getTradeId());
                        entrustRecordService.save(fundEntrust);

                        rabbitTemplate.convertAndSend("myExchange","fundRedemptionTask",fundEntrust);
                    }
                    //将委托发往股票交易所
                    for (EntrustRecordEntity stockEntrust:fundEntrustList) {

                        stockEntrust.setTradeId(tradeRecordEntity.getTradeId());
                        entrustRecordService.save(stockEntrust);

                        rabbitTemplate.convertAndSend("myExchange","stockRedemptionTask",stockEntrust);
                    }

                    LinkedHashMap comBaseInfo = new LinkedHashMap();
                    //组合名称
                    String comBaseName = "";
                    //用户修改后的组合
                    if(oldComBaseId == comBaseId){
                        comBaseInfo = (LinkedHashMap) combinationFeignService.getComBaseInfo(comBaseId).get("combination");
                        comBaseName = (String) comBaseInfo.get("comBaseName");
                    }else {
                        comBaseInfo = (LinkedHashMap) combinationFeignService.getComBaseInfo(newCombinationInfoService.getById(comBaseId).getComBaseId()).get("combination");
                        comBaseName = (String) comBaseInfo.get("comBaseName");
                    }

                    SimpleDateFormat df1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //下单时间
                    String createTime = df1.format(tradeRecordEntity.getGmtCreate());
                    //金额
                    BigDecimal tradeAmount = tradeRecordEntity.getTradeAmoount();
                    //交易类型
                    String tradeType = "赎回";
                    SimpleDateFormat df2=new SimpleDateFormat("MM-dd");
                    //确认份额日期
                    String confirmShareTime = df2.format(new Date(tradeRecordEntity.getGmtCreate().getTime() + 1 * 24 * 60 * 60 * 1000));
                    //查看收益日期
                    String viewEarningsTime = df2.format(new Date(tradeRecordEntity.getGmtCreate().getTime() + 2 * 24 * 60 * 60 * 1000));
                    return CommonResult.success("赎回委托已提交，处理中")
                            .put("comBaseName",comBaseName)
                            .put("createTime",createTime)
                            .put("tradeAmount",tradeAmount)
                            .put("tradeType",tradeType)
                            .put("confirmShareTime",confirmShareTime)
                            .put("viewEarningsTime",viewEarningsTime);
                }else {
                    return CommonResult.error(201,"委托失败,请重新提交");
                }
            }
        }
    }

    /**
     * 调整仓位比例
     * @return
     */
    @Transactional
    @PostMapping("/adjustmentShare")
    public CommonResult adjustmentShare(@RequestBody CombinationProductDto combinationProduct){
        //新组合实体
        NewCombinationInfoEntity newCombinationInfoEntity = new NewCombinationInfoEntity();
        //财富账号实体
        WealthAccountEntity wealthAccountEntity = new WealthAccountEntity();
        //调仓记录实体
        AdjustmentRecord adjustmentRecord = new AdjustmentRecord();
        //成分产品实体集合
        ArrayList<ProductRatioDto> productRatioDtos = (ArrayList<ProductRatioDto>) combinationProduct.getProductRatioDtoList();
        //股票委托列表
        ArrayList<EntrustRecordEntity> stockEntrustList = new ArrayList<>();
        //基金委托列表
        ArrayList<EntrustRecordEntity> fundEntrustList = new ArrayList<>();
        //原组合id
        Long comBaseId = combinationProduct.getComBaseId();
        //用户id
        Long userId = combinationProduct.getUserId();
        //当前账户总金额
        BigDecimal amount = BigDecimal.valueOf(0);
        //保存新组合flag
        boolean saveNewComFlag = true;
        //保存成分产品flag
        boolean saveProductFlag = true;
        //保存委托flag
        boolean saveEntrustFlag = true;
        //更新交易人数
        dataFeginService.updateCombinationDynamicInfo(comBaseId,0,0,1,0);
        //检查是否有修改后的记录
        Long newBaseId = verifyUpdateNewComId(userId,comBaseId);

        //已经存在自定义的组合
        if(newBaseId != comBaseId){
            newCombinationInfoEntity.setNewComId(newBaseId);
        }
        //创建修改后的组合
        newCombinationInfoEntity.setComBaseId(comBaseId);
        newCombinationInfoEntity.setUserId(userId);
        newCombinationInfoEntity.setIsUsed(2);

        saveNewComFlag = newCombinationInfoService.saveOrUpdate(newCombinationInfoEntity);

        //获取当前账户总仓位
        wealthAccountEntity = wealthAccountService.getWealthAccount(comBaseId,userId);
        amount = wealthAccountEntity.getWealthAccountAmoount();
        //标记财富账号被修改过
        wealthAccountEntity.setIsUpdate(1);
        wealthAccountService.saveOrUpdate(wealthAccountEntity);
        //创建调仓记录
        String timeUUid = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String logicId = "QMA" + timeUUid;

        adjustmentRecord.setAdjustStatus(1);
        adjustmentRecord.setLogicId(logicId);
        adjustmentRecord.setWealthAccountId(wealthAccountEntity.getWealthAccountId());
        adjustmentRecord.setUserId(userId);
        adjustmentRecord.setNewCombinationId(newCombinationInfoEntity.getNewComId());

        adjustmentRecordDao.insert(adjustmentRecord);

        //新建成分产品
        for (ProductRatioDto productRatioDto:productRatioDtos) {

            NewCombinationShareEntity newCombinationShareEntity = new NewCombinationShareEntity();
            NewCombinationShareEntity ShareEntity = newCombinationShareService.getShareEntity(productRatioDto.getProductCode(),newCombinationInfoEntity.getNewComId());


            if(ShareEntity!= null){
                newCombinationShareEntity = ShareEntity;
                log.info(ShareEntity.toString());
            }

            newCombinationShareEntity.setNewComId(newCombinationInfoEntity.getNewComId());
            newCombinationShareEntity.setProTsCode(productRatioDto.getProductCode());
            newCombinationShareEntity.setNewComShareRadio(productRatioDto.getShareRadio());

            saveProductFlag &= newCombinationShareService.saveOrUpdate(newCombinationShareEntity);

            //组装委托单
            EntrustRecordEntity entrustRecordEntity = new EntrustRecordEntity();

            entrustRecordEntity.setEntrustStatus(1);
            entrustRecordEntity.setWealthAccountId(wealthAccountEntity.getWealthAccountId());
            entrustRecordEntity.setUserId(userId);
            entrustRecordEntity.setRecordId(adjustmentRecord.getAdjustId());

            //份额计算
            BigDecimal partAmount = amount.multiply(productRatioDto.getShareRadio());
            BigDecimal closePrice = BigDecimal.valueOf((Double) dataFeginService.getPrice(productRatioDto.getProductCode()).get("closePrice"));
            BigDecimal share = partAmount.divide(closePrice,0,1);
            //获取该成分产品对应的持仓
            Long proId = Long.valueOf(String.valueOf(combinationFeignService.getProId(productRatioDto.getProductCode()).get("proId")));
            WealthPositionEntity wealthPositionEntity = wealthPositionService.getPosition(userId,wealthAccountEntity.getWealthAccountId(),proId);
            //设置产品编号
            entrustRecordEntity.setProId(proId);
            //产品类型
            Integer proType = (Integer) combinationFeignService.getProType(proId).get("proType");

            //股票类型
            if(1 == proType){
                String SElogicId = "SE" + UUID.randomUUID();
                entrustRecordEntity.setLogicId(SElogicId);
            }else {
                String FElogicId = "FE" + UUID.randomUUID();
                entrustRecordEntity.setLogicId(FElogicId);
            }

            log.info("现在的份额"+String.valueOf(share));
            log.info("之前的份额"+ String.valueOf(wealthPositionEntity.getPositionShare()));

            //当前产品升仓
            if(share.compareTo(BigDecimal.valueOf(wealthPositionEntity.getPositionShare())) == 1){
                log.info("我是升");
                entrustRecordEntity.setEntrustType(2);
                entrustRecordEntity.setEntrustShare(Integer.valueOf(share.subtract(BigDecimal.valueOf(wealthPositionEntity.getPositionShare())).toString()));
                entrustRecordEntity.setEntrustAmount(partAmount.subtract(wealthPositionEntity.getPositionAmount()));
                //股票类型
                if(1 == proType){
                    stockEntrustList.add(entrustRecordEntity);
                    //基金类型
                }else {
                    fundEntrustList.add(entrustRecordEntity);
                }

                saveEntrustFlag &= entrustRecordService.save(entrustRecordEntity);
                //当前产品减仓
            }else if(share.compareTo(BigDecimal.valueOf(wealthPositionEntity.getPositionShare())) == -1){
                log.info("我是降");
                entrustRecordEntity.setEntrustType(1);
                entrustRecordEntity.setEntrustShare(wealthPositionEntity.getPositionShare() - Integer.valueOf(share.toString()));
                entrustRecordEntity.setEntrustAmount(wealthPositionEntity.getPositionAmount().subtract(partAmount));
                //股票类型
                if(1 == proType){
                    stockEntrustList.add(entrustRecordEntity);
                    //基金类型
                }else {
                    fundEntrustList.add(entrustRecordEntity);
                }
                saveEntrustFlag &= entrustRecordService.save(entrustRecordEntity);
            }
        }
        //保存失败
        if(!(saveNewComFlag && saveProductFlag)){
            return CommonResult.error(501,"系统故障，数据库保存失败");
        }

        log.info(String.valueOf(777777));
        //将委托发往消息队列
        if(saveEntrustFlag){
            for (EntrustRecordEntity stockEntrust:stockEntrustList) {
                rabbitTemplate.convertAndSend("myExchange","stockAdjust",stockEntrust);
            }

            for (EntrustRecordEntity fundEntrust:fundEntrustList){
                rabbitTemplate.convertAndSend("myExchange","fundAdjust",fundEntrust);
            }
        }
        log.info(String.valueOf(888888));
        LinkedHashMap comBaseInfo = (LinkedHashMap) combinationFeignService.getComBaseInfo(comBaseId).get("combination");
        //组合名称
        String comBaseName = (String) comBaseInfo.get("comBaseName");

        SimpleDateFormat df1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //下单时间
        String createTime = df1.format(adjustmentRecord.getGmtCreate());
        //交易类型
        String tradeType = "调仓";

        SimpleDateFormat df2=new SimpleDateFormat("MM-dd");
        //确认份额日期
        String confirmShareTime = df2.format(new Date(adjustmentRecord.getGmtCreate().getTime() + 1 * 24 * 60 * 60 * 1000));
        //查看收益日期
        String viewEarningsTime = df2.format(new Date(adjustmentRecord.getGmtCreate().getTime() + 2 * 24 * 60 * 60 * 1000));

        return CommonResult.success("调仓委托已提交，处理中")
                .put("comBaseName",comBaseName)
                .put("createTime",createTime)
                .put("tradeType",tradeType)
                .put("confirmShareTime",confirmShareTime)
                .put("viewEarningsTime",viewEarningsTime);
    }

    /**
     * 获取当前持仓产品的调仓记录
     * @param userId
     * @param wealthAccountId
     * @return
     */
    @RequestMapping("/adjustmentRecordLists")
    public CommonResult getAdjustmentRecordLists(Long userId,Long wealthAccountId){
        //调仓记录信息列表
        ArrayList<AdjustmentRecord> adjustmentRecordArrayList = new ArrayList<>();
        //组合信息实体
        CombinationBaseInfoEntity combinationBaseInfoEntity = new CombinationBaseInfoEntity();

        QueryWrapper<AdjustmentRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId)
                    .eq("wealth_account_id",wealthAccountId);
        //获取交易信息列表
        adjustmentRecordArrayList = (ArrayList<AdjustmentRecord>) adjustmentRecordDao.selectList(queryWrapper);

        WealthAccountEntity wealthAccountEntity = wealthAccountService.getById(wealthAccountId);
        //组合实体
        LinkedHashMap comBaseInfo = new LinkedHashMap();
        //组合名称
        String comBaseName = "";

        comBaseInfo = (LinkedHashMap) combinationFeignService.getComBaseInfo(wealthAccountEntity.getComBaseId()).get("combination");
        comBaseName = (String) comBaseInfo.get("comBaseName");

        return CommonResult.success()
                .put("adjustmentRecords",adjustmentRecordArrayList)
                .put("comBaseName",comBaseName);
    }

    /**
     * 调仓记录详情以及委托列表
     * @param adjustId
     * @return
     */
    @RequestMapping("/adjustmentRecord")
    public CommonResult getAdjustmentRecord(Long adjustId){
        //调仓记录实体
        AdjustmentRecord adjustmentRecord = new AdjustmentRecord();
        //委托列表
        ArrayList<EntrustRecordEntity> entrustRecordEntityArrayList =  new ArrayList<>();
        //返回结果集
        ArrayList<EntrustRecordDto> entrustRecordDtoArrayList = new ArrayList<>();

        adjustmentRecord = adjustmentRecordDao.selectById(adjustId);

        WealthAccountEntity wealthAccountEntity = wealthAccountService.getById(adjustmentRecord.getWealthAccountId());
        //组合实体
        LinkedHashMap comBaseInfo = new LinkedHashMap();
        //组合名称
        String comBaseName = "";

        comBaseInfo = (LinkedHashMap) combinationFeignService.getComBaseInfo(wealthAccountEntity.getComBaseId()).get("combination");
        comBaseName = (String) comBaseInfo.get("comBaseName");

        entrustRecordEntityArrayList = entrustRecordService.getEntrustRecordListByAdjustId(adjustId);

        for (EntrustRecordEntity entrustRecordEntity:entrustRecordEntityArrayList) {
            EntrustRecordDto entrustRecordDto = new EntrustRecordDto();

            String proName = productLibraryInfoDao.selectById(entrustRecordEntity.getProId()).getProName();
            String proTsCode = productLibraryInfoDao.selectById(entrustRecordEntity.getProId()).getProTsCode();

            entrustRecordDto.setEntrustAmount(entrustRecordEntity.getEntrustAmount());
            entrustRecordDto.setEntrustStatus(entrustRecordEntity.getEntrustStatus());
            entrustRecordDto.setProName(proName);
            entrustRecordDto.setProTsCode(proTsCode);

            entrustRecordDtoArrayList.add(entrustRecordDto);
        }

        if(adjustmentRecord != null && !entrustRecordEntityArrayList.isEmpty()){
            return CommonResult.success().put("adjustmentRecord",adjustmentRecord)
                                         .put("entrustList",entrustRecordDtoArrayList)
                                         .put("comBaseName",comBaseName);
        }else {
            return CommonResult.error(201,"无此调仓记录");
        }
    }

    /**
     * 获取当前仓位信息
     * @param wealthAccountId
     * @param userId
     * @return
     */
    @RequestMapping("/getWealthPositionInfoList")
    public CommonResult getWealthPositionInfoList(Long wealthAccountId, Long userId){
        //财富账号实体类
        WealthAccountEntity wealthAccountEntity =  new WealthAccountEntity();
        //持仓列表
        ArrayList<WealthPositionEntity> wealthPositionEntityArrayList = new ArrayList<>();
        //dto列表
        ArrayList<PositionInfoDto> positionInfoDtoArrayList = new ArrayList<>();

        wealthAccountEntity = wealthAccountService.getById(wealthAccountId);

        wealthPositionEntityArrayList = wealthPositionService.getListByWealthAccountId(wealthAccountId);

        for (WealthPositionEntity wealthPositionEntity:wealthPositionEntityArrayList) {
            PositionInfoDto positionInfoDto = new PositionInfoDto();

            String proName = productLibraryInfoDao.selectById(wealthPositionEntity.getProId()).getProName();
            String proTsCode = productLibraryInfoDao.selectById(wealthPositionEntity.getProId()).getProTsCode();

            positionInfoDto.setProName(proName);
            positionInfoDto.setProTsCode(proTsCode);
            positionInfoDto.setAmount(wealthPositionEntity.getPositionAmount());

            BigDecimal ratio = wealthPositionEntity.getPositionAmount().divide(wealthAccountEntity.getWealthAccountAmoount(),2, RoundingMode.HALF_UP);
            positionInfoDto.setRatio(String.valueOf(ratio.multiply(BigDecimal.valueOf(100)))+"%");

            positionInfoDtoArrayList.add(positionInfoDto);
        }

        if(!positionInfoDtoArrayList.isEmpty()){
            return CommonResult.success().put("positionInfoDtoArrayList",positionInfoDtoArrayList);
        }else {
            return CommonResult.error(201,"无持仓信息");
        }

    }

    /**
     * 获取队列中消息数量
     * @param queue
     * @return
     */
    public int getMessageCount(String queue) {
        AMQP.Queue.DeclareOk declareOk = rabbitAdmin.getRabbitTemplate().execute(new ChannelCallback<AMQP.Queue.DeclareOk>() {
            public AMQP.Queue.DeclareOk doInRabbit(Channel channel) throws Exception {
                return channel.queueDeclarePassive(queue);
            }
        });
        return declareOk.getMessageCount();
    }

    /**
     * 验证该用户是否有自定义过该组合
     * @param userId
     * @param comBaseId
     * @return
     */
    public Long verifyUpdateNewComId(Long userId,Long comBaseId){
        //组合id
        Long id = Long.valueOf(0);

        id = newCombinationInfoService.getNewComId(userId,comBaseId);

        return id;
    }
}
